<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32 ST7789图片转换工具</title>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --background-color: #ecf0f1;
            --text-color: #34495e;
            --success-color: #2ecc71;
            --error-color: #e74c3c;
        }
        .size-input {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }

        .size-input input {
            width: 80px;
            margin: 0 10px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .size-input label {
            margin-right: 5px;
        }

        .content > div {
            width: 45%;
        }

        textarea#cCode {
            width: 95%;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 8px;
        }

        h1, h3 {
            text-align: center;
            color: var(--secondary-color);
        }

        h1 {
            margin-bottom: 10px;
        }

        h3 {
            margin-top: 0;
            margin-bottom: 20px;
        }

        a {
            color: var(--primary-color);
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        .upload-section {
            text-align: center;
            margin-bottom: 30px;
        }

        .size-input {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }

        .size-input input {
            width: 80px;
            margin: 0 10px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .size-input label {
            margin-right: 5px;
        }

        .content {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
        }

        .content > div {
            width: 45%;
        }

        h2 {
            color: var(--primary-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
            margin-top: 0;
            margin-bottom: 20px;
        }

        input[type="file"] {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: inline-block;
        }

        textarea {
            width: 100%;
            height: 400px;
            padding: 15px;
            font-size: 14px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f9f9f9;
            resize: vertical;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-family: 'Courier New', Courier, monospace;
        }

        .btn {
            display: inline-block;
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin-left: 10px;
        }

        .btn:hover {
            background-color: #2980b9;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            font-weight: bold;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .notification.show {
            opacity: 1;
        }

        .notification.success {
            background-color: var(--success-color);
        }

        .notification.error {
            background-color: var(--error-color);
        }

        .loading-spinner {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #imagePreview {
            max-width: 20%;
            margin-top: 20px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>ESP32 ST7789图片转换工具</h1>
        <h3><a href="https://www.qingningz.cn/" target="_blank">青柠博客出品</a></h3>
        
        <div class="upload-section">
            <h2>ST7789图片转换工具</h2>
            <p>将 JPG/PNG/BMP 转换为 RGB565 !图片不能大于你ST7789屏幕尺寸!</p>
            <div class="size-input">
                <label for="width">宽度:</label>
                <input type="number" id="width" placeholder="宽度">
                <label for="height">高度:</label>
                <input type="number" id="height" placeholder="高度">
            </div>
            <input type="file" id="imageInput" accept="image/*">
            <button class="btn" id="convertBtn">开始转换</button>
            <img id="imagePreview" alt="Image preview" />
        </div>
        
        <div class="content">
            <div>
                <h2>调用示例代码</h2>
                <textarea id="outputText" placeholder="这里会生成调用示例代码" readonly></textarea>        
            </div>
            <div>
                <h2>Arduino/ESP32 图片库代码</h2>
                <textarea id="cCode" placeholder="这里会生成图片库代码" readonly></textarea>
            </div>
        </div>
    </div>

    <div id="notification" class="notification"></div>
    <div id="loadingSpinner" class="loading-spinner">
        <div class="spinner"></div>
    </div>

    <script>
        let lastWidth, lastHeight;
        let originalImage = null;

        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = `notification ${type} show`;
            setTimeout(() => {
                notification.className = 'notification';
            }, 3000);
        }

        function showLoading(show) {
            const spinner = document.getElementById('loadingSpinner');
            spinner.style.display = show ? 'flex' : 'none';
        }

        function cropImage(image, width, height) {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = width;
            canvas.height = height;

            // Calculate aspect ratios
            const imageAspectRatio = image.width / image.height;
            const targetAspectRatio = width / height;

            let drawWidth, drawHeight, drawX, drawY;

            if (imageAspectRatio > targetAspectRatio) {
                // Image is wider, crop the sides
                drawHeight = image.height;
                drawWidth = image.height * targetAspectRatio;
                drawX = (image.width - drawWidth) / 2;
                drawY = 0;
            } else {
                // Image is taller, crop the top and bottom
                drawWidth = image.width;
                drawHeight = image.width / targetAspectRatio;
                drawX = 0;
                drawY = (image.height - drawHeight) / 2;
            }

            ctx.drawImage(image, drawX, drawY, drawWidth, drawHeight, 0, 0, width, height);

            return canvas.toDataURL('image/png');
        }

        document.getElementById('imageInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    originalImage = new Image();
                    originalImage.onload = function() {
                        const preview = document.getElementById('imagePreview');
                        preview.src = event.target.result;
                        preview.style.display = 'block';
                    }
                    originalImage.src = event.target.result;
                }
                reader.readAsDataURL(file);
            }

            if (lastWidth && lastHeight) {
                document.getElementById('width').value = lastWidth;
                document.getElementById('height').value = lastHeight;
            }
        });

        document.getElementById('convertBtn').addEventListener('click', function() {
            const width = parseInt(document.getElementById('width').value);
            const height = parseInt(document.getElementById('height').value);

            if (!originalImage) {
                showNotification('请先选择一个图片文件。', 'error');
                return;
            }

            if (!width || !height) {
                showNotification('请输入图片的宽度和高度。', 'error');
                return;
            }

            lastWidth = width;
            lastHeight = height;

            const croppedImageData = cropImage(originalImage, width, height);

            showLoading(true);

            // Convert base64 to blob
            fetch(croppedImageData)
                .then(res => res.blob())
                .then(blob => {
                    const formData = new FormData();
                    formData.append('image', blob, 'cropped_image.png');
                    formData.append('width', width);
                    formData.append('height', height);

                    return fetch('/get_rgb565', {
                        method: 'POST',
                        body: formData
                    });
                })
                .then(response => response.json())
                .then(data => {
                    document.getElementById('outputText').value = data.logs || 'No logs available';
                    document.getElementById('cCode').value = data.c_code || 'No C code available';
                    showNotification('转换成功！', 'success');
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('转换图片时出错', 'error');
                })
                .finally(() => {
                    showLoading(false);
                });
        });
    </script>
</body>
</html>

